#include "iapclientadapter.h"
#include <QSettings>
#include <QDebug>

#define KSettingUserDighestKey "accountdigest"
#define KSettingCompanyName "NokiaProjects"
#define KSettingApplicationName "qt_iap_bridge"

Q_DECLARE_METATYPE(IAPClient::ProductDataList)  //to be able to transfer data this type with Qt::QueuedConnection

IAPClientAdapter::IAPClientAdapter(MIAPClientAdapterObserver& observer) :
    QObject(NULL),
    iObserver(&observer)
{
    // required so that IAPClient::ProductData can be queued in the signal
    qRegisterMetaType<IAPClient::ProductDataHash>("IAPClient::ProductDataHash");
    qRegisterMetaType<IAPClient::UserAndDeviceDataHash>("IAPClient::ProductDataHash");

    iap_client = new IAPClient(this); //NOTE QObject destruction : it will be deleted when 'this' deletes all childs

    connect(iap_client, SIGNAL(purchaseCompleted( int , QString, QString)), this,
            SLOT(purchaseCompleted( int , QString, QString)),Qt::QueuedConnection);
    connect(iap_client, SIGNAL(purchaseFlowFinished(int)), this, SLOT(purchaseFlowFinished(int)), Qt::QueuedConnection);
    connect(iap_client, SIGNAL(productDataReceived( int, QString, IAPClient::ProductDataHash)), this,
            SLOT(productDataReceived(int, QString, IAPClient::ProductDataHash)), Qt::QueuedConnection);
    connect(iap_client, SIGNAL(userAndDeviceDataReceived(int,
                  QString, IAPClient::UserAndDeviceDataHash)),
                        this, SLOT(userAndDeviceDataReceived(int,
                                   QString, IAPClient::UserAndDeviceDataHash)));

    QSettings settings(KSettingCompanyName, KSettingApplicationName);
    userAuth = settings.value(KSettingUserDighestKey, "").toString();
}

TInt IAPClientAdapter::purchaseProduct(QString productId)
{
    qDebug() << "IAPClientAdapter::getUserAndDeviceId";
    return (iap_client->purchaseProduct(productId, IAPClient::NoForcedRestoration));
}

TInt IAPClientAdapter::getProductData(QString productId)
{
    qDebug() << "IAPClientAdapter::getUserAndDeviceId";
    return (iap_client->getProductData(productId));
}

TInt IAPClientAdapter::getUserAndDeviceId()
{
    qDebug() << "IAPClientAdapter::getUserAndDeviceId";

    if(!userAuth.isEmpty()){
        iObserver->Notify(KErrNone, userAuth);
        return KErrNotFound;
    }

    return (iap_client->getUserAndDeviceId(IAPClient::DefaultAuthentication));
}

void IAPClientAdapter::productDataReceived(int requestId, QString status, IAPClient::ProductDataHash data)
{
    iObserver->ProductDataNotify(requestId,
                               ((status.compare("OK") == 0) ? data.value("info").toString() : status),
                               data.value("description").toString(),
                               data.value("shortdescription").toString(),
                               data.value("price").toString());
}

void IAPClientAdapter::userAndDeviceDataReceived(int requestId, QString status,
                                IAPClient::UserAndDeviceDataHash response)
{

    if(status.compare("SilentOperationFailed") == 0){
        iap_client->getUserAndDeviceId(IAPClient::DefaultAuthentication);
        // NOTE: you have to sign in to OVI Store client
        // to have getUserAndDeviceId(IAPClient::OnlyInSilentAuthentication)
        // working properly. Otherwise use explicit user authentication
        return;
    }

    if(status.compare("OK") != 0){
        iObserver->Notify(requestId, status);
        return;
    }

    userAuth = response.value("accountdigest").toString();
    QSettings settings(KSettingCompanyName, KSettingApplicationName);
    settings.setValue(KSettingUserDighestKey, userAuth);
    iObserver->Notify(requestId, userAuth);
}

void IAPClientAdapter::purchaseCompleted(int requestId, QString status, QString purchaseTicket)
{
    iPurchaseDeferStat = ((status.compare("OK") == 0) ? purchaseTicket : status);
}

void IAPClientAdapter::purchaseFlowFinished(int requestId)
{
    iObserver->Notify(requestId, iPurchaseDeferStat);
}
